package common.util.mybatis.plus.logic;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Controller;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author 刘波
 * @param <M>
 * @param <T>
 */
public class LogicBaseServiceImpl<M extends BaseMapper<T>,T> extends ServiceImpl<M,T> implements LogicBaseService<T>{



    /**
     * 分批次查询, 把 传入 对象 拆分成多份进行查询
     * @param rows
     * @param fieldName
     * @param size
     * @return
     */
    @Override
    public List<T> queryInBatch(List rows, String fieldName , Integer size){
        return queryInBatch(rows, fieldName,new QueryWrapper<T>(),size);
    }

    /**
     * 分批次查询, 把 传入 对象 拆分成多份进行查询
     * @param rows
     * @param queryWrapper
     * @param fieldName
     * @param size
     * @return
     */
    @Override
    public List<T> queryInBatch(List rows, String fieldName, QueryWrapper<T> queryWrapper, Integer size) {
        List<T> result = new ArrayList<>();
        List<List> list = splitCollectors(rows, size);

        for (List row : list) {
            QueryWrapper<T> wrapper = queryWrapper.clone();
            wrapper.in(fieldName,row);
            result.addAll(this.list(wrapper));
        }
        return result;
    }

    public <T> List<List<T>> splitCollectors(Collection<T> collection,Integer size){
        List<List<T>> list = new ArrayList<>();
        List<T> rows = new ArrayList<>();
        for (T t : collection) {
            rows.add(t);
            if(rows.size()%size ==0){
                list.add(rows);
                rows = new ArrayList<>();
            }
        }
        if (null != rows && rows.size() >0){
            list.add(rows);
        }
        return list;
    }

    /**
     * 分批次查询, 把 传入 对象 拆分成多份进行查询
     * @param rows
     * @param fieldName
     * @return
     */
    @Override
    public List<T> queryInBatch(List rows, String fieldName ){
        return queryInBatch(rows, fieldName,new QueryWrapper<T>());
    }

    /**
     * 分批次查询, 把 传入 对象 拆分成多份进行查询
     * @param rows
     * @param fieldName
     * @param queryWrapper
     * @return
     */
    @Override
    public List<T> queryInBatch(List rows, String fieldName, QueryWrapper<T> queryWrapper) {
        return queryInBatch(rows, fieldName,new QueryWrapper<T>(),1000);
    }

}
